// challeng/pages/cplay/cplay.js
var app = getApp();
var answerTimer = null;
var music_ing= false
function playAudio(url,cb){
  wx.getSystemInfo({
  success: function (res) {
    if (res.system.indexOf('iOS') >= 0) {
          wx.playBackgroundAudio({
            dataUrl: url,
            complete: function () {
              wx.onBackgroundAudioStop(function (res) {
                if(cb) cb();
              });
            }
          });
        } else {
          var m = wx.getBackgroundAudioManager()
          m.src = url;
          m.onStop(function (res) {
            if (cb) cb();
          });
          m.onEnded(function (res) {
            if (cb) cb();
          });
        }
      }
    })
}
function stopMusic(that){
	if(!music_ing){
		that.setData({
			zhuan:false,
		});
	}
	else{
		music_ing = false;
	}
}
Page({
	onShareAppMessage:function(){
	  var that = this;
	  var mid = that.data.mem.id;
	  var sharedata = that.data.shareData;
	  sharedata.path = 'challeng/pages/index/index?mid='+mid+'&gType=6';
	  return {
		  title: sharedata.title,
	     // desc: sharedata.desc,
	      path: sharedata.path,
	      imageUrl:sharedata.pic,
	      success(res){
	    	  var shareTicket = res.shareTickets[0] // 获取 shareTicket
	    	  wx.getShareInfo({
	              shareTicket: shareTicket,
	              complete(res) {
	            	  app.util.request({
		    	        url: 'entry/wxapp/ReAnswer',
		    	        data: {
		    	            m : 'junsion_challeng',
		    	            t : 1,
		    	            mid : that.data.openid,
		    	            iv : res.iv,
		    	            encryptedData : res.encryptedData,
		    	        },
		    	        success: function (res) {
		    	        	if (res.data.code == 2) {
		                        //获得提示
		    	        		  var cur_num = parseInt(that.data.cur_num);
		    	          		  var right_anwer = app.strencode(that.data.problem[cur_num].answer,that.data.str_time);
		    	          		  var right_anwer=right_anwer.split(""); 
		    	          		  var userSel = that.data.answer;
		    	            	  var cur_i = parseInt(that.data.cur_i);
		    	            	  for(var ii=0;ii<userSel.length;ii++){
		    	            		  if(!userSel[ii] || userSel[ii]==''){
		    	            			userSel[ii] = right_anwer[ii];
		    	            			break;
		    	            		  }
		    	            	  }
		    	            	  cur_i++;
		    	              	  that.setData({answer:userSel,cur_i:cur_i,reamin:true});
		    	    	    } 
		    	        	else{
		    	        		 wx.showModal({title:res.data.msg,showCancel:false});
		    	        	}
		    	        }
		    	    }); 
	                
	              }
	          });
	      },
	      fail: function(res) {
	        // 转发失败
	    	  console.log(res);
	      }
	  }
  },
  data: {
	game_bg:'',
	openid:'',
  	mem:{},
  	total:0,
  	cur_num:0,
  	cur_i:0,
  	times:[],
  	g_nums:[],
	resettime:5,
	answerIng:false,
	problem:[],
	answer:[],
	zhuan:false,
	reamin:false,
	m_bg:'',
	m_stop:'',
	m_play:'',
	str_time:'',
	gametoken:'',
	g_shoushi:'',
	g_close:'',
  	
  	beginCountDown: 5,//游戏开始--倒计时
    gamingStatus: 'notBegin',//游戏状态4个。notBegin未开始，running正在运行，fail挑战失败,success挑战成功
  },
  onLoad: function (options) {
	  var that = this;
	  wx.showLoading({title:'数据加载中...'});
	  app.sysInit(this,function(res){
		  app.getUserInfo(function (res) {
			  var openid = res['openid'];
			  //获取分享内容
			  app.getShareData(function(res){
				  that.setData({shareData:res.data});
			  },openid,6);
			  
			  that.setData({openid:openid});
			  app.util.request({
				  url: 'entry/wxapp/cplay',
				  data: {
					  m: 'junsion_challeng',
					  t: 1,
					  openid:openid,
					  game:6,
				  },
				  success: function (res) {
					  wx.hideLoading();
					  if(res.data.code==0 || res.data.code==2){
						  var code = res.data.code;
						  wx.showModal({
							  title:res.data.msg,
							  showCancel:false,
							  success: function(res) {
								  wx.showLoading({title:'数据加载中...'});
								  if(code==2)
									  var url = '../index/index?gobuy=1';
								  else var url = '../index/index';
								  wx.redirectTo({
									  url: url
								  })
							  }
						  });
					  }
					  else{
						  console.log(res);
						  that.setData({
							  game_bg:res.data.game_bg,
							  gametoken:res.data.gametoken,
							  str_time:res.data.str_time,
							  mem:res.data.mem,
							  m_bg:res.data.m_bg,
							  m_stop:res.data.m_stop,
							  m_play:res.data.m_play,
							  beginCountDown:res.data.down,
							  total:res.data.total,
							  times:res.data.times,
							  g_nums:res.data.g_nums,
							  g_close:res.data.g_close,
							  g_shoushi:res.data.g_shoushi,
							  problem:res.data.problem,
							  answer:res.data.problem[0].check_answer,
							  answerIng:false,
							  zhuan:false,
						  });
						  var check_answer = res.data.problem[0].check_answer;
						  if(check_answer.length<=2){
							  that.setData({
								  reamin:true,
							  });
						  }
						  if(parseInt(res.data.times[0])>0){
							  that.setData({
								  resettime:res.data.times[0],
							  });
						  }
						  else if(parseInt(res.data.times[1])>0){
							  that.setData({
								  resettime:res.data.times[1],
							  });
						  }
						  else if(parseInt(res.data.times[2])>0){
							  that.setData({
								  resettime:res.data.times[2],
							  });
						  }
						  else{
							  that.setData({
								  resettime:5,
							  });
						  }
						  that.beginCountDown(res.data.down);//游戏主入口
					  }
				  },
			  });
		  });
	  });
	  var music = wx.getStorageSync('music');
      that.setData({
		  err_music:music.err_music,
	  });
	  
  },
  onReady: function () {
	  var that=this;
      this.errAudio = wx.createAudioContext('errAudio')
  },
  goPlay:function(){
	  var that=this;
	  if(that.data.zhuan){
		  that.setData({
			  zhuan:false,
		  });
		  wx.stopBackgroundAudio()
	  }
	  else{
		  that.setData({
			  zhuan:true,
		  });
		  var cur_num = parseInt(that.data.cur_num);
		  playAudio(that.data.problem[cur_num].music,function(){stopMusic(that)});
	  }
  },
  goAdd:function(e){
	  var that = this;
	  var dataset = e.currentTarget.dataset;
  	  var index = dataset.index;
  	  var userSel = that.data.answer;
  	  if(userSel[index]){
  		  userSel[index] = '';
  		  var cur_i = parseInt(that.data.cur_i);
  		  cur_i--;
  		  that.setData({answer:userSel,cur_i:cur_i});
  	  }
  },
  goCheck:function(e){
	  var that = this;
  	  var dataset = e.currentTarget.dataset;
  	  var index = dataset.index;
  	  var cur_num = parseInt(that.data.cur_num);
  	  var answers = that.data.problem[cur_num].answers;
  	  var userSel = that.data.answer;
  	  var cur_i = parseInt(that.data.cur_i);
  	  for(var ii=0;ii<userSel.length;ii++){
  		  if(!userSel[ii] || userSel[ii]==''){
  			userSel[ii] = answers[index];
  			break;
  		  }
  	  }
  	  cur_i++;
  	  that.setData({answer:userSel,cur_i:cur_i});
  	  if(cur_i==userSel.length){
  		if(that.data.answerIng) return false;
  		that.setData({answerIng:true});
  		clearInterval(answerTimer);//用户选择答案之后就清除定时器，防止超时失败
  		//判断答案是否正确
  		var user_anwer = '';
  		for(var jj=0;jj<userSel.length;jj++){
  			user_anwer+=userSel[jj];
  		}
  		var right_anwer = app.strencode(that.data.problem[cur_num].answer,that.data.str_time);
  		if(that.data.zhuan){
			music_ing = true;
		}
  		wx.stopBackgroundAudio()
  		if(right_anwer!=user_anwer){
  			app.tzfail(that,6);//挑战失败
  		}
  		else{
  			cur_num++;
  			if (cur_num == parseInt(that.data.total)) {
				app.checkReward(that,6,cur_num);//中奖了
				return false;
			}
			if(parseInt(that.data.g_nums[0])>=cur_num){
				var now_times=that.data.times[0];
			}
			else if(parseInt(that.data.g_nums[1])>=cur_num){
				var now_times=that.data.times[1];
			}
			else if(parseInt(that.data.g_nums[2])>=cur_num){
				var now_times=that.data.times[2];
			}
			else{
				var now_times=5;
			}
  			if(cur_num % 10 == 0){
  				//获取新的题目
  				app.util.request({
  	  				url: 'entry/wxapp/checkcplay',
  	  				data: {
  	  					m: 'junsion_challeng',
  	  					t: 1,
  	  					mid:that.data.mem.id,
  	  					str_time:that.data.str_time,
  	  					game:6,
  	  				},
  	  				success: function (res) {
  	  					if(res.data.code==1){
	  	  					that.setData({
	  	  						problem: that.data.problem.concat(res.data.problem),
		  	  	            });
	  	  					that.timeCountDown(now_times);
	  	  					that.setData({answer:that.data.problem[cur_num].check_answer,zhuan:true,reamin:false,cur_i:0,answerIng:false,cur_num:cur_num});
		  	  				playAudio(that.data.problem[cur_num].music,function(){stopMusic(that)});
  	  					}
  	  					else{
  	  						wx.showModal({
  	  							title:res.data.msg,
  	  							showCancel:false,
  	  							success: function(res) {
  	  								wx.redirectTo({
  	  									url: '../index/index'
  	  								})
  	  							}
  	  						});
  	  					}
  	  				}
  	  			});
  			}
  			else{
  				that.timeCountDown(now_times);
				that.setData({answer:that.data.problem[cur_num].check_answer,zhuan:true,reamin:false,cur_i:0,answerIng:false,cur_num:cur_num});
				playAudio(that.data.problem[cur_num].music,function(){stopMusic(that)});
  			}
  		}
	  }
  },
  onUnload: function(){
	  clearInterval(answerTimer);
  },
  timeCountDown:function(myTime){
  	var that=this;
  	if(answerTimer){
  		clearInterval(answerTimer);
  		that.setData({ resettime: myTime });
  	}
		answerTimer = setInterval(function () {
  		if(that.data.answerIng){
  			return false;
  		}
  		that.setData({ resettime: --myTime });
  		if (myTime <= 0) {
  			//时间到，失败
  			clearInterval(answerTimer);
  			//失败处理
  			  wx.pauseBackgroundAudio()
  			  app.tzfail(that,6);//挑战失败
  		}
  	}, 1000);
  	
  },
//游戏开始倒计时
  beginCountDown:function(countTime){
      var that=this;
      var timer = setInterval(function () {
          that.setData({ beginCountDown: --countTime });
          if (countTime <= 0) {
              clearInterval(timer);
              that.setData({
                  gamingStatus:'running'
              });
              that.timeCountDown(parseInt(that.data.resettime));//游戏主入口
          }
      }, 1000)
  }

})